package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Stockorders;
import com.example.mapper.GoodsMapper;
import com.example.mapper.StockordersMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@Service
public class StockordersService {

    @Resource
    private StockordersMapper stockordersMapper;

    @Resource
    private GoodsMapper goodsMapper;

    public List<LinkedHashMap<String, Object>> getExportData() {
        List<Stockorders> stockordersList = stockordersMapper.selectAll(null);
        if (stockordersList == null || stockordersList.isEmpty()) {
            throw new RuntimeException("数据库中无数据");
        }
        List<LinkedHashMap<String, Object>> exportData = new ArrayList<>();
        for (Stockorders stock : stockordersList) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            map.put("订单编号", stock.getOrderNo());
            map.put("供应商ID", stock.getSupplierId());
            map.put("商品名称", stock.getName());
            map.put("数量", stock.getCount());
            map.put("总金额", stock.getTotal());
            map.put("时间", stock.getTime());
            exportData.add(map);
        }
        return exportData;
    }


    public void add(Stockorders stockorders) {
        stockorders.setOrderNo(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        stockordersMapper.insert(stockorders);
        goodsMapper.updateStock(stockorders.getSupplierId(), stockorders.getCount());
    }

    public PageInfo<Stockorders> selectPage(Integer pageNum, Integer pageSize, Stockorders stockorders) {
        PageHelper.startPage(pageNum, pageSize);
        List<Stockorders> list = stockordersMapper.selectAll(stockorders);
        return PageInfo.of(list);
    }

    public void update(Stockorders stockorders) {
        stockordersMapper.updateById(stockorders);
    }

    public void deleteById(Integer id) {
        stockordersMapper.deleteById(id);
    }

    public List<Stockorders> selectAll(Stockorders stockorders) {
        return stockordersMapper.selectAll(stockorders);
    }
}
